import axios from 'axios'
import { ElMessage } from "element-plus";
import {Utils} from "@/utils/utils";
import {ConfigUtils} from "./ConfigUtils";
import {useUserStore} from "@/store/user";


const download = axios.create({
  baseURL: ConfigUtils.CONFIG.baseUrl, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
});

// request interceptor
download.interceptors.request.use(
  config => {
    const userStore = useUserStore();
    if (userStore.token && config.headers) {
      config.headers['Authorization'] = 'Bearer ' + userStore.token;
      config.headers['account'] = userStore.loginname;
    }
    config.baseURL = ConfigUtils.CONFIG.baseUrl;
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
download.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  // @ts-ignore
  response => {
    const data = response.data;

    // if the custom code is not 20000, it is judged as an error.
    if (response.status === 200 && data) {
      return response;
    } else {
      ElMessage({
        message: '文件下载失败',
        type: 'error',
        duration: 5 * 1000,
        center: true
      })
    }
  },
  error => {
    console.log('err' + error) // for debug
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 5 * 1000,
      center: true
    })
    return Promise.reject(error)
  }
)

export default download
